import { createOssUploadToken } from './api.js';

// 获取登陆code
export const getCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: (loginRes) => {
				if(loginRes?.code) {
					resolve(loginRes.code);
				} else {
					reject(loginRes?.errMsg || '获取code失败');
				}
			},
			fail: () => {
				reject('获取code失败');
			},
			complete: () => {
				reject('获取code失败');
			}
		})
	})
}

// 获取token
export const getToken = () => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'token',
			success: (token) => {
				resolve({token: token});
			},
			fail: (err) => {
				reject({ err })
			}
		})
	})
}

// 是否登录
export const isLogin = () => {
	let token = uni.getStorageSync('token');
	
	if(!token) {
		return false;
	}
	
	return true;
}

// 获取用户信息
export const getUserInfoDetail = () => {
	let userInfo = uni.getStorageSync('userInfo');
	
	if(!userInfo) return '';
	try {
		return JSON.parse(userInfo);
	} catch(e) {
		return '';
	}
}

// 未登录跳转登录页面
export const navigateToLogin = (callback) => {
	uni.navigateTo({
		url: "/pages/login/login"
	})
	
}

// 获取文件上传密钥
export const fetchOssUploadToken = () => {
	return createOssUploadToken();
}

// 上传图片
export const uploadFile = (url) => {
	return new Promise(async (resolve, reject) => {
		// const [errToken, tokenData] = await to(getToken());
		const [err, uploadData] = await to(fetchOssUploadToken());
		const { ossaccessKeyId, policy, signature, dir, host, expire } = uploadData.data;
		let urlArr = url.split('.');
		let prefix = urlArr[urlArr.length - 1] || 'png';
		const key = `${dir}${new Date().getTime()}${Math.random()}.${prefix}`;
		const queryInfo = {
			name: url,
			key: key,
			policy: policy,
			OSSAccessKeyId: uploadData.data.ossaccessKeyId,
			signature: signature,
			expire: expire,
		}
		
		uni.uploadFile({
			// url: 'https://api.zhaodazi.club/dev-api/app/file/oss/uploadFile2Oss',
			url: host,
			filePath: url,//res.tempFilePaths[0],
			fileType: 'image',
			name: 'file',
			formData:queryInfo,
			// header: {
			// 	'content-type': 'multipart/form-data',
			// 	'Authorization': 'Bearer ' + tokenData?.token?.data
			// },
			success: (res) => {
				resolve(host+"/"+key);
			},
			fail: (err) => {
				reject({ msg: err?.msg || `文件上传失败${url}` });
			}
		});
	})
}

// 上传文件之后处理
export const uploadAfter = async (file) => {
	return new Promise(async resolve => {
		console.log(file);
		let _paths = file?.map(item => item.url);
		
		let paths = await compressAllImage(file, _paths);
		console.log(paths, 'paths');
		
		let promises = Promise.all(paths.map(path => uploadFile(path)));
		const [errFile, dataFile] = await to(promises);
		if(errFile) return;
		
		// let fileList = dataFile?.map(item => {
		// 	const { data } = item || {};
		// 	const fileData = JSON.parse(data);
		// 	console.log(data, fileData)
		// 	const { data: _data, success, msg } = fileData;
		// 	if(success) {
		// 		return {
		// 			id: _data.id,
		// 			url: _data.url,
		// 			originalName: _data.originalName
		// 		};
		// 	} else {
		// 		return {
		// 			msg
		// 		}
		// 	}
		//
		// })

		let fileList = dataFile?.map(item => {
			return {
				id: 'p' + Math.random() + '',
				url: item,
			};
		})
		resolve(fileList);
	})
	
}

export const compressAllImage = async (file, paths) => {
	return new Promise(async (resolve, reject) => {
		let _paths = [];
		_paths = await Promise.all(paths.map((path, index) => compressImage(path, file[index].size)));
		resolve(_paths);
	})
}

// 图片压缩
export const compressImage = async (path, originSize) => {
	let size = 1 * 1024 * 1024;	// 大于1M，压缩
	return new Promise((resolve, reject) => {
		if(originSize <= size) {
			return resolve(path);
		}
		uni.compressImage({
		  src: path,
		  quality: 70,
			compressedWidth: 1000,
		  success: res => {
		    console.log(res.tempFilePath)
				if(res.tempFilePath) {
					resolve(res.tempFilePath);
				} else {
					resolve(path)
				}
		  },
			fail: () => {
				resolve(path);
			}
		})
	})
}

/**
 * 用于优化await捕获异常的方式
 * 使用：
		interface ServerResponse {
			test: number;
		}
		interface FetchError {
			msg: string;
		}
		const p = Promise.resolve({test: 123});
		const [err, data] = await to<ServerResponse>(p);
		if(err) return message.error(err?.msg);
		console.log(data.test);
 * @param promise
 * @param errorExt
 * @returns
 */
export const to = (
	promise,
	errorExt,
) => {
	return promise
		.then(data => [null, data])
		.catch(err => {
			if (errorExt) {
				const parsedError = Object.assign({}, err, errorExt);
				return [parsedError, undefined];
			}

			return [err, undefined];
		});
}

// rpx转px
export const rpxToPx = (rpx) => {
  const screenWidth = uni.getSystemInfoSync().screenWidth
  return (screenWidth * Number.parseInt(rpx)) / 750
}

// px转rpx
export const pxToRpx = (px) => {
  const screenWidth = uni.getSystemInfoSync().screenWidth
  return (750 * Number.parseInt(px)) / screenWidth
}

//获取系统信息
export const getSystemInfo = () => {
	return uni.getSystemInfoSync();
}

// 获取时间
export const getDataFormat = (date) => {
	if(!date) return '';
	let _date = new Date(date);
	return _date.getFullYear() + '-' + (_date.getMonth() + 1) + '-' + _date.getDate();
}

// 校验表单
export const checkForm = (formFieldMsg, formData) => {
	for(let i = 0; i < formFieldMsg.length; i++) {
		const { field, msg } = formFieldMsg[i];
		if(!formData[field]) {
			return msg;
		}
	}
	return false;
}
